# getAllPairs.py 修改导入顺序（关键修复）
import os
import sys
import django

# 必须先设置路径再初始化Django
BASE_DIR = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))  # 向上三级到项目根目录
sys.path.insert(0, BASE_DIR)  # 确保优先查找项目目录

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "application.settings")
django.setup()  # ✅ 必须在所有模型导入之前

from config import BinanceConfig
from binance.client import Client
import datetime
import time
from tradingPairs.models import TradingPairs


# 获取所有交易对信息
def get_all_pairs(api_key, api_secret, proxies):
    # 初始化客户端
    client = Client(api_key=api_key, api_secret=api_secret, requests_params={'proxies': proxies} if proxies else None)

    # 获取交易所信息
    exchange_info = client.get_exchange_info()
    symbols_info = exchange_info['symbols']

    # 获取当前时间，并向下取整到最近的整点
    now = datetime.datetime.utcnow()
    latest_hour = now.replace(minute=0, second=0, microsecond=0)

    for symbol_data in symbols_info:
        symbol = symbol_data['symbol']
        is_trading = symbol_data['status'] == 'TRADING'

        try:
            # 获取最早可用的 K 线数据时间戳（毫秒）
            earliest_ts = client._get_earliest_valid_timestamp(symbol, Client.KLINE_INTERVAL_1DAY)
            earliest_dt = datetime.datetime.utcfromtimestamp(earliest_ts / 1000)
        except Exception as e:
            # 如果获取失败，设置为 None
            earliest_dt = None
        if is_trading:
            TradingPairs.objects.create(
                trading_pair=symbol,
                data_beings=earliest_dt,
                data_end=latest_hour,
                is_trade=is_trading
            )

        # 避免请求过于频繁，遵守 API 限制
        time.sleep(0.1)

    # return result


if __name__ == "__main__":
    # API密钥
    api_key = BinanceConfig.API_KEY
    api_secret = BinanceConfig.API_SECRET
    proxies = BinanceConfig.PROXIES
    # 获取交易对信息
    get_all_pairs(api_key, api_secret, proxies)

    # for info in symbols_info:
    #     print(
    #         f"交易对: {info['symbol']}, 最早时间: {info['earliest_timestamp']}, 最近整点: {info['latest_hour']}, 可交易: {info['is_trading']}")
